package com.rest.demo.ctrl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Result;

import org.dom4j.io.XMLResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.oxm.Marshaller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.rest.demo.model.Authentication;
import com.rest.demo.model.Profile;
import com.rest.demo.model.ProfileVersion;

@RequestMapping("/video")
@Controller
public class KorisnikController {

    @Autowired
    private Marshaller xstreamMarshaller;

    @RequestMapping(value = "/login", produces = "application/xml")
    public void login(HttpServletRequest request, HttpServletResponse response) {

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        Authentication authentication = new Authentication();

        if (username != null && password != null && username.equals("a") && password.equals("a")) {
            authentication.setKey("12345676");
        }
        try {
            Result result = new XMLResult(response.getWriter());
            xstreamMarshaller.marshal(authentication, result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/version", produces = "application/xml")
    public void checkVersion(HttpServletResponse response) {

        int ver = 1;
        ProfileVersion version = new ProfileVersion();
        version.setVersion(ver);

        try {
            Result result = new XMLResult(response.getWriter());
            xstreamMarshaller.marshal(version, result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/update", produces = "text/html")
    public void getProfiles(HttpServletResponse response) {

        List<Profile> pofiles = new ArrayList<Profile>();

        pofiles.add(new Profile("low", "-o"));
        pofiles.add(new Profile("hi", "-v"));

        try {
            Result result = new XMLResult(response.getWriter());
            xstreamMarshaller.marshal(pofiles, result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
